package com.zhida.jiyangcenter.modle

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.InputFilter
import android.view.MotionEvent
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.EditText
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.utils.*
import chooongg.http.APIException
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.vehicle.inspection.api.toRequestBody
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.WebNoTokenActivity
import com.zhida.jiyangcenter.api.APIZaxiang
import com.zhida.jiyangcenter.api.BaseAPI
import com.zhida.jiyangcenter.api.HospitalEntity
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.order.adapter.CommentAdapter
import com.zhida.jiyangcenter.order.adapter.PhotoInfo
import com.zhida.jiyangcenter.utils.FilterUtil
import com.zhida.jiyangcenter.utils.GlideEngine
import com.zhida.jiyangcenter.utils.request
import kotlinx.android.synthetic.main.activity_medical.*
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList


@TitleBar(false)
@ContentLayout(R.layout.activity_medical)
class MedicalActivity : BaseActivity() {
    val dataYiyuan = ArrayList<String>()

    val dataKeshi = ArrayList<String>()
    lateinit var adaptersYiyuan: ArrayAdapter<String>
    lateinit var adaptersKeshi: ArrayAdapter<String>
    private val mPhotoInfos = ArrayList<PhotoInfo>()
    private val MAX_NUM = 3
    private var mTempPhotoInfo: PhotoInfo? = null
    private var mPhotoIndex = 1
    private var mAdapter: CommentAdapter? = null

    override fun initConfig(savedInstanceState: Bundle?) {
        title_bar.title("就医服务").navigationIcon(R.drawable.iv_back_fill) {
            finish()
        }.operationText("服务说明") {
            startActivity<WebNoTokenActivity> {
                putExtra(
                    WebNoTokenActivity.URL,
                    "http://beauty.hebzd.com/static/xieyi/userAgreement.html"
                )
                putExtra(WebNoTokenActivity.TITLE, "服务说明")
            }
        }.getOperationTextView().apply {
            setTextColor(resColor(R.color.white))
        }
        tv_commit.setOnClickListener {
            when {
                time.isEmpty() -> toast("请选择您的预约时间")
                edit_name.text.isNullOrEmpty() -> toast("请填写您的真实姓名")
                edit_cardID.text.isNullOrEmpty() -> toast("请填写您的身份证号码")
                edit_phone.text.isNullOrEmpty() -> toast("请填写您的手机号码")
                else -> {
                    commit()
                }
            }
        }

        recycler_view.layoutManager = GridLayoutManager(this, 3)
        addAddImageData()
        mAdapter = CommentAdapter(mPhotoInfos, object : CommentAdapter.DelPhotoListener {
            override fun delPhoto(path: String) {
                delItem(path)
            }

            override fun addPhoto() {
                selectImage()
            }
        })
        recycler_view.adapter = mAdapter
        edit_name.setOnTouchListener { view, event ->
            //触摸的是EditText而且当前EditText能够滚动则将事件交给EditText处理。否则将事件交由其父类处理
            if (view.getId() == R.id.edit_miaoshu && canVerticalScroll(edit_name)) {
                view.getParent().requestDisallowInterceptTouchEvent(true)
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    view.getParent().requestDisallowInterceptTouchEvent(false)
                }
            }
            false
        }
        edit_name.filters = arrayOf(
            FilterUtil.getInputFilter(
                this,
                "不支持输入表情或者特殊符号", FilterUtil.MATCHER_DEFAULT
            ), InputFilter.LengthFilter(200)
        )
        tv_time.setOnClickListener {
            val selectedDate = Calendar.getInstance()
            val startDate = Calendar.getInstance()
            startDate.set(
                selectedDate.get(Calendar.YEAR),
                selectedDate.get(Calendar.MONTH),
                selectedDate.get(Calendar.DAY_OF_MONTH) + 3
            );
            val endDate = Calendar.getInstance()
            endDate.set(
                selectedDate.get(Calendar.YEAR),
                selectedDate.get(Calendar.MONTH),
                selectedDate.get(Calendar.DAY_OF_MONTH) + 10
            );


            val pvTime = TimePickerBuilder(this,
                OnTimeSelectListener { date, v -> //选中事件回调
                    time = date2String(
                        date,
                        SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                    )
                    tv_time.text = time
                })
                .setType(booleanArrayOf(true, true, true, true, true, true)) // 默认全部显示
                .setCancelText("取消") //取消按钮文字
                .setSubmitText("确认") //确认按钮文字
                .setTitleSize(14) //标题文字大小
                .setSubCalSize(14)
                .setContentTextSize(14)
                .setTitleText("请选择您预约的时间") //标题文字
                .setOutSideCancelable(false) //点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false) //是否循环滚动
                .setTitleColor(Color.BLACK) //标题文字颜色
                .setSubmitColor(Color.BLACK) //确定按钮文字颜色
                .setCancelColor(Color.BLACK) //取消按钮文字颜色
                .setTitleBgColor(resColor(R.color.white)) //标题背景颜色 Night mode
                .setBgColor(resColor(R.color.colorBack)) //滚轮背景颜色 Night mode
                .setTextColorCenter(resColor(R.color.textColor))
                .setTextColorOut(resColor(R.color.textGray))
                .setDate(selectedDate) // 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate) //起始终止年月日设定
                .setType(booleanArrayOf(true, true, true, false, false, false))
                .setLabel("年", "月", "日", "时", "分", "秒") //默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(true) //是否显示为对话框样式
                .build()
            pvTime.show()
        }
        getData()
    }

    private fun commit() {
        val datas = HashMap<String, RequestBody>()
        for (i in 0 until mPhotoInfos.size) {
            if (mPhotoInfos[i].localUrl != "发布") {
                val cardFrontFile = File(mPhotoInfos[i].localUrl)
                val requestFrontBody = RequestBody.create(MultipartBody.FORM, cardFrontFile)
                datas["picture" + (i+1) + "\"; filename=\"" + cardFrontFile.name] =
                    requestFrontBody
            }
        }
        lifecycleScope.request({
            APIZaxiang.service().doctorServeAdd(
                yiyuan.toRequestBody(),
                keshi.toRequestBody(),
                time.toRequestBody(),
                edit_name.text.toString().toRequestBody(),
                edit_cardID.text.toString().toRequestBody(),
                edit_phone.text.toString().toRequestBody(),
                edit_opinion.text.toString().toRequestBody(),
                datas
            )
        }, object : BaseAPI<Any>() {
            override fun onSuccess(t: Any?, state: Int, msg: String) {
                tipSuccess(msg)
                finish()
            }

            override fun onError(e: APIException) {
                tipFail(e.eMessage)
            }

        })
    }

    var yiyuan = ""
    var keshi = ""
    private fun getData() {
        lifecycleScope.request({ APIZaxiang.service().hospital() },
            object : BaseAPI<List<HospitalEntity>>() {
                override fun onSuccess(t: List<HospitalEntity>?, state: Int, msg: String) {
                    dataYiyuan.clear()
                    t?.forEach {
                        dataYiyuan.add(it.hospital_name!!)
                    }

                    //将可选内容与ArrayAdapter连接起来
                    adaptersYiyuan =
                        ArrayAdapter(context, android.R.layout.simple_spinner_item, dataYiyuan)
                    //设置下拉列表的风格
                    adaptersYiyuan.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
                    //将adapter 添加到spinner中
                    spinner_yiyuan.adapter = adaptersYiyuan
                    //添加事件Spinner事件监听
                    spinner_yiyuan.onItemSelectedListener =
                        object : AdapterView.OnItemSelectedListener {
                            override fun onNothingSelected(parent: AdapterView<*>?) {

                            }

                            override fun onItemSelected(
                                parent: AdapterView<*>?,
                                view: View?,
                                positions: Int,
                                id: Long
                            ) {
                                yiyuan = t?.get(positions)?.hospital_id ?: ""
                                dataKeshi.clear()
                                t?.get(positions)?.department?.forEach {
                                    dataKeshi.add(it.department_name!!)
                                }
                                //将可选内容与ArrayAdapter连接起来
                                adaptersKeshi = ArrayAdapter(
                                    context,
                                    android.R.layout.simple_spinner_item,
                                    dataKeshi
                                )
                                //设置下拉列表的风格
                                adaptersKeshi.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
                                //将adapter 添加到spinner中
                                spinner_keshi.adapter = adaptersKeshi
                                //添加事件Spinner事件监听
                                spinner_keshi.onItemSelectedListener =
                                    object : AdapterView.OnItemSelectedListener {
                                        override fun onNothingSelected(parent: AdapterView<*>?) {

                                        }

                                        override fun onItemSelected(
                                            parent: AdapterView<*>?,
                                            view: View?,
                                            position: Int,
                                            id: Long
                                        ) {
                                            keshi =
                                                t?.get(positions)?.department?.get(position)?.department_id
                                                    ?: ""
                                        }
                                    }
                            }
                        }
                    dataKeshi.clear()
                    t?.get(0)?.department?.forEach {
                        dataKeshi.add(it.department_name!!)
                    }
                    //将可选内容与ArrayAdapter连接起来
                    adaptersKeshi = ArrayAdapter(
                        context,
                        android.R.layout.simple_spinner_item,
                        dataKeshi
                    )
                    //设置下拉列表的风格
                    adaptersKeshi.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
                    //将adapter 添加到spinner中
                    spinner_keshi.adapter = adaptersKeshi
                    //添加事件Spinner事件监听
                    spinner_keshi.onItemSelectedListener =
                        object : AdapterView.OnItemSelectedListener {
                            override fun onNothingSelected(parent: AdapterView<*>?) {

                            }

                            override fun onItemSelected(
                                parent: AdapterView<*>?,
                                view: View?,
                                position: Int,
                                id: Long
                            ) {
                                keshi =
                                    t?.get(0)?.department?.get(position)?.department_id
                                        ?: ""
                            }
                        }

                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }
            })
    }

    var time = ""
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1004) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                val selectList = PictureSelector.obtainMultipleResult(data)
                addPhotoNotify(
                    when {
                        !selectList[0].compressPath.isNullOrEmpty() -> selectList[0].compressPath
                        !selectList[0].cutPath.isNullOrEmpty() -> selectList[0].cutPath
                        !selectList[0].androidQToPath.isNullOrEmpty() -> selectList[0].androidQToPath
                        else -> selectList[0].path
                    }
                )
            }
        }
    }

    /**
     * 在页面显示图片
     *
     * @param path
     */
    private fun addPhotoNotify(path: String) {
        if (mPhotoInfos.size >= 1) {
            mPhotoInfos.remove(mPhotoInfos[mPhotoInfos.size - 1])
        }
        if (path.isNotEmpty()) {
            mTempPhotoInfo = PhotoInfo(path, mPhotoIndex)
            mPhotoInfos.add(mTempPhotoInfo!!)
            mPhotoIndex++
        }
        if (mPhotoInfos.size < MAX_NUM) {
            addAddImageData()
        }
        recycler_view.adapter = mAdapter
    }


    fun selectImage() {
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofImage())
            .selectionMode(PictureConfig.SINGLE)
            .loadImageEngine(GlideEngine.createGlideEngine())
            .previewImage(false)
            .isCamera(true)
            .minimumCompressSize(200)
            .compress(true)
            .isZoomAnim(true)
            .withAspectRatio(1, 1)
            .circleDimmedLayer(true)
            .showCropFrame(false)
            .showCropGrid(false)
            .isDragFrame(true)
            .rotateEnabled(true)
            .scaleEnabled(true)
            .forResult(1004)
    }

    /**
     * EditText竖直方向能否够滚动
     *
     * @param editText 须要推断的EditText
     * @return true：能够滚动   false：不能够滚动
     */
    private fun canVerticalScroll(editText: EditText): Boolean {
        //滚动的距离
        val scrollY = editText.scrollY
        //控件内容的总高度
        val scrollRange = editText.layout.height
        //控件实际显示的高度
        val scrollExtent =
            editText.height - editText.compoundPaddingTop - editText.compoundPaddingBottom
        //控件内容总高度与实际显示高度的差值
        val scrollDifference = scrollRange - scrollExtent

        return if (scrollDifference == 0) {
            false
        } else scrollY > 0 || scrollY < scrollDifference - 1

    }


    /**
     * 删除图片
     *
     * @param path
     */
    private fun delItem(path: String) {
        for (info in mPhotoInfos) {
            if (info.localUrl.equals(path)) {
                mPhotoInfos.remove(info)
                break
            }
        }
        if (!"发布".equals(mPhotoInfos[mPhotoInfos.size - 1].localUrl)) {
            addAddImageData()
        }
        mAdapter?.notifyDataSetChanged()
    }

    /**
     * 添加“+选择图片”
     */
    private fun addAddImageData() {
        val addInfo = PhotoInfo("发布", -1)
        mPhotoInfos.add(addInfo)
    }
}